package com.ronan.client;

import com.ronan.client.handler.RIMClientHandlerInitializer;
import com.ronan.common.protocol.RIMProtocol;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * FileName    : com.ronan.client
 * Description :
 *
 * @author : ronan
 * @version : 1.0
 * Create Date : 2021/3/1 16:53
 **/
@Slf4j
@Component
public class IMClient {

    private static Channel channel = null;

    public void start() throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress("192.168.72.24",6789))
                .handler(new RIMClientHandlerInitializer());

        // 建立连接 连接到远程节点，阻塞等待，直到连接完成
        ChannelFuture channelFuture = bootstrap.connect().sync();
        channel = channelFuture.channel();

        channelFuture.addListener(future -> {
            if (future.isSuccess()) {
                log.info("RIM client success!!!");
            }
        });
    }


    /**
     * 发送消息
     *
     * @param protocol 协议
     */
    public void send(RIMProtocol protocol) {
        log.info("发送消息 ==> {}",protocol.getBody());
        channel.writeAndFlush(protocol);
    }

}
